from flask import Flask, render_template
from flask_socketio import SocketIO
import json,time
app = Flask(__name__)
app.config['SECRET_KEY'] = '!SPEAKERKEY!'
socketio = SocketIO(app)
history=""
bann=["操","肏","cao","Cao","日","CAO","alert","br",".."]
lastsendpool={}
useridpool = []


@app.route('/')
def page():
	return render_template('index.html')

@app.route('/test/')
def test():
	return render_template('nb.html')


def broadcast(text):
	socketio.emit('send',{"data":text},broadcast=True)

def checkban(t):
	for i in bann:
		if i in t:
			return False
	return True
def checkfreq(time,user):
	if user not in useridpool:
		return 0
	if not user in lastsendpool.keys():
		return 1
	if (time - lastsendpool[user]) < 0 :
		return 0
	if (time - lastsendpool[user]) <= 1.0 :
		return 3
	if (time - lastsendpool[user]) <= 3.0 :
		return 0
	return 1

@socketio.on('connect')
def openpage():
	socketio.emit('openconn',{"data":"open"})

@socketio.on('addpool')
def addpool(uid):
	if uid not in useridpool:
		useridpool.append(uid)
	print(useridpool)

@socketio.on('exitroom')
def exitroom(key):
	print("Logout:",key)
	lastsendpool.pop(key)
	useridpool.remove(key)

@socketio.on('recieve')
def recieve(txt):
	deny=0
	reclst=list(txt)
	jsons = reclst[0]
	currtime = time.time()
	checkok=checkfreq(currtime,reclst[1])
	if jsons!= history and jsons!="" and checkok==1:
		if checkban(jsons):
			#print(jsons)
			broadcast(jsons)
			lastsendpool[reclst[1]] = currtime
			#history = jsons
	elif checkok==3:
		lastsendpool[reclst[1]]=currtime+10.0
		socketio.emit('send',{"data":"您因请求频率过快已被暂时冻结"})

if __name__ == '__main__':
	socketio.run(app,host="0.0.0.0",debug=True)